# Copyright 2009 http://www.yuntien.com
# Licensed under the Apache License, Version 2.0

from google.appengine.api import users
from auth_def import *

def get_role(obj=None):
    if users.is_current_user_admin():
        return ROLE_ADMIN
  
    if users.get_current_user():
        # TODO: need to ensure that obj has an author property
        if obj is not None and users.get_current_user() == obj.get_owner().ga:
            return ROLE_OWNER
        return ROLE_USER
  
    return ROLE_GUEST

def comp_role(role1, role2):
    rating = {
        ROLE_ADMIN    : 9,
        ROLE_OWNER    : 8,
        ROLE_USER     : 7,
        ROLE_GUEST    : 0,
    }

    return rating[role1] > rating[role2]

def get_auth(obj, auth_model=AUTH_MODEL, check_parent=False, get_role=get_role, com_role=comp_role):
    # cls should be a subclass of db.Model
    cls, obj = obj
    role = get_role(obj)
  
    while obj is not None and check_parent == True and obj.get_parent() is not None:
        obj = obj.get_parent()
        role_tmp = get_role(obj)
        if comp_role(role_tmp, role):
            role = role_tmp    
  
    return auth_model[cls.kind()][role]

def check_auth(obj, operation, auth_model=AUTH_MODEL, check_parent=False, get_role=get_role):
    # cls should be a subclass of db.Model
    cls, obj = obj
    role = get_role(obj)
    
    if auth_model[cls.kind()][role][operation] == True:
        return True
  
    while obj is not None and check_parent == True and obj.get_parent() is not None:
        obj = obj.get_parent()
        role = get_role(obj)
        
        if auth_model[cls.kind()][role][operation] == True:
            return True
  
    return False
